package com.sinog.core.util;

import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @desc 文件工具类
 * @author lzq
 * @date 2022/12/12 11:51
 */
@Slf4j
public class FileUtils {

    private static final String MSIE_STR = "MSIE";
    private static final String TRIDENT_STR = "Trident";

    /**
     * 整合版文件下载
     * @param request request
     * @param resp resp
     * @param filePath filePath
     * @param filename filename
     */
    public static void downloadFile(HttpServletRequest request,HttpServletResponse resp,String filePath,String filename) throws java.io.UnsupportedEncodingException {
        //获取浏览器
        String userAgent = request.getHeader("User-Agent");
        if(!userAgent.contains("Windows")){
            PrintWriter writer = null;
            resp.setContentType("text/html; charset=utf-8");
            try {
                writer = resp.getWriter();
                writer.println("<script type=\"text/javascript\">alert('目前仅支持Windows安装包下载，其他客户端操作系统请自行下载或联系管理员');window.history.back(-1);</script>");
                writer.flush();
            } catch(IOException e) {
                log.error("发生异常",e);
            } finally {
                Objects.requireNonNull(writer).close();
            }
        }
        if(userAgent.contains(MSIE_STR) || userAgent.contains(TRIDENT_STR)) {
            //IE浏览器处理
            filename = URLEncoder.encode(filename,"UTF-8");
        } else {
            // 非IE浏览器的处理
            filename = new String(filename.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
        }
        File file = new File(filePath);
        //判断文件父目录是否存在
        if(file.exists()) {
            resp.setContentType("application/force-download");
            resp.setHeader("Content-Disposition","attachment;filename=" + filename);
            resp.setContentLength((int)file.length());
            byte[] buffer = new byte[1024];
            //文件输入流
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                os = resp.getOutputStream();
                int len;
                while(-1 != (len = bis.read(buffer))) {
                    os.write(buffer,0,len);
                }
                resp.flushBuffer();
            } catch(IOException e) {
                PrintWriter writer = null;
                resp.setContentType("text/html; charset=utf-8");
                try {
                    writer = resp.getWriter();
                    writer.println("<script type=\"text/javascript\">alert('文件下载失败，请稍后重试');window.history.back(-1);</script>");
                    writer.flush();
                } catch(IOException e1) {
                    log.error("发生异常",e1);
                } finally {
                    Objects.requireNonNull(writer).close();
                }
                log.error("发生异常",e);
            } finally {
                try {
                    if(null != bis) {
                        bis.close();
                    }
                } catch(IOException e) {
                    log.error("发生异常",e);
                }
                try {
                    if(null != os) {
                        os.close();
                    }
                } catch(IOException e) {
                    log.error("发生异常",e);
                }
                try {
                    if(null != fis) {
                        fis.close();
                    }
                } catch(IOException e) {
                    log.error("发生异常",e);
                }
            }
        } else {
            PrintWriter writer = null;
            resp.setContentType("text/html; charset=utf-8");
            try {
                writer = resp.getWriter();
                writer.println("<script type=\"text/javascript\">alert('文件不存在，请联系管理员');window.history.back(-1);</script>");
                writer.flush();
            } catch(IOException e) {
                log.error("发生异常",e);
            } finally {
                Objects.requireNonNull(writer).close();
            }
        }
    }
}